/**
 * LinkedLST
 * May 20, 2011
 * Conversion.java - Definition for a number of methods to manipulate data.
 */

package edu.washington.cs.labspecimentransport.ops;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.conn.ConnectTimeoutException;

import edu.washington.cs.labspecimentransport.data.DataQuery;
import edu.washington.cs.labspecimentransport.dataobjects.Identifier;
import edu.washington.cs.labspecimentransport.dataobjects.Item;

/**
 * Definition for a number of methods to manipulate data
 */
public class Conversion {
    /**
     * Converts a list of Item to a list of Item.id. Assumes that all items in the 
     * list are well-formed.
     * 
     * @param itemList a list of items
     * @return a list of item ids
     */
    public static ArrayList<Integer> convertItemsToItemIds(List<Item> itemList) {
    	ArrayList<Integer> idList = new ArrayList<Integer>();
    	for (Item i : itemList) {
    		idList.add(i.getId());
    	}
    	return idList;
    }    
	
	/**
     * Converts a list of Item.id into a map that associates each id 
     * to its corresponding barcode(s).
     * 
     * @param idList list of item ids
     * @return map with mappings from id to barcode
	 * @throws ConnectTimeoutException 
     */
    public static HashMap<Integer, ArrayList<String>> 
    		convertItemIdListToBarcodeList(List<Integer> idList) 
    			throws ConnectTimeoutException {
    	DataQuery query = DataQuery.getInstance();
    	HashMap<Integer,ArrayList<String>> barcodeMap = new HashMap<Integer, ArrayList<String>>();
    	for (Integer i : idList) {
    		if (i != null) {
    			barcodeMap.put(i, identifiersToBarcodes(query.getBarcodesByItemId(i)));
    			android.util.Log.d("ClientView", "ID: " + i + ", Barcode: " + barcodeMap.get(i));
    		}
    	}
    	return barcodeMap;
    }
    
    /**
     * Converts a list of Identifiers to a list of barcodes.
     * 
     * @param identifiers list of Identifiers to convert
     * @return list of barcodes
     */
    public static ArrayList<String> identifiersToBarcodes(List<Identifier> identifiers) {
    	ArrayList<String> result = new ArrayList<String>();
    	for(Identifier id : identifiers) {
    		result.add(id.getIdentifier_value());
    	}
    	return result;
    }
    
    /**
     * Returns true if the given map contains a list value that contains the given barcode.
     */
    public static boolean mapContainsBarcode(HashMap<Integer, ArrayList<String>> barcodeMap, String barcode) {
    	ArrayList<String> barcodeList;
    	for (Integer i : barcodeMap.keySet()) {
    		barcodeList = barcodeMap.get(i);
    		if (barcodeList.contains(barcode)) {
    			return true;
    		}
    	}
    	return false;
    }
}
